<!--
  * 代理商表
  *
  * @Author:    zwd
  * @Date:      2025-01-23 04:08:26
-->
<template>
  <a-modal :title="form.id ? '修改规则' : '新增规则'" :width="800" :open="visibleFlag" @cancel="onClose" :maskClosable="false" :destroyOnClose="true">
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="180" label-align="top">
      <a-row>
        <a-col :span="12">
          <a-form-item label="计费类型" name="type">
            <a-select v-model:value="form.type" :options="BILLING_TYPE" placeholder="请选择" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="计费名称" name="title">
            <a-input v-model:value="form.title" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="结算模式" name="settleType">
            <a-select v-model:value="form.settleType" :options="SETTLE_TYPE" placeholder="请选择" />
          </a-form-item>
        </a-col>
        <a-col :span="form.chargeType == '3' ? 8 : 12">
          <a-form-item label="计费模式" name="chargeType" style="width: 100%">
            <a-select v-model:value="form.chargeType" :options="CHARGE_TYPE" placeholder="请选择" />
          </a-form-item>
        </a-col>
        <a-col :span="4" v-if="form.chargeType == '3'">
          <a-form-item label="" name="stairType" style="width: 100%">
            <a-select v-model:value="form.stairType" :options="STAIR_TYPE" placeholder="请选择" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="计费对象" name="chargeUserType">
            <a-select v-model:value="form.chargeUserType" :options="CHARGE_USER_TYPE" placeholder="请选择" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="状态" name="status">
            <a-switch v-model:checked="form.status" :checkedValue="1" :unCheckedValue="0" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <template #footer>
      <a-space>
        <!-- <a-button @click="onReset">重置</a-button> -->
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script setup>
  import { reactive, ref, computed, watch } from 'vue'
  import { message } from 'ant-design-vue'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { chargeUpdate, chargeInsert, chargeFindId } from '/@/api/business/b-operation/channel/charge-api.js'
  import { smartSentry } from '/@/lib/smart-sentry'
  import { isUndefined, cloneDeep, isEmpty } from 'lodash'
  import {
    BILLING_TYPE, //计费类型
    CHARGE_USER_TYPE, //计费对象
    CHARGE_TYPE, //计费模式
    SETTLE_TYPE, //'结算模式'
    STAIR_TYPE, //'阶梯类型'
  } from '/@/constants/dict'

  const props = defineProps({
    open: {
      type: Boolean,
      default: false,
      required: true,
    },

    // 表单类型 add/update/view
    // add: 新增, update: 编辑,view: 查看
    formType: {
      type: String,
      default: 'add',
    },
    formId: {
      type: Object,
      default: () => {
        return null
      },
    },
  })
  // ------------------------ 事件 ------------------------
  const emits = defineEmits(['update:open', 'ok'])

  // ------------------------ 显示与隐藏 ------------------------
  // 是否显示
  const visibleFlag = computed({ get: () => props.open, set: (val) => emits('update:open', val) })

  async function show(id) {
    if (!isEmpty(id)) {
      try {
        SmartLoading.show()
        const response = await chargeFindId({ id: id })
        if (response && response.data) {
          form.value = response.data
        }
      } catch (error) {
        smartSentry.captureError(error)
      } finally {
        SmartLoading.hide()
      }
    }
  }

  function onClose() {
    onReset()
    visibleFlag.value = false
  }

  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref()

  const formDefault = {
    type: undefined, //计费类型
    title: undefined, //计费名称
    settleType: undefined, //结算模式
    chargeType: undefined, //计费模式
    stairType: undefined,
    chargeUserType: undefined, //计费对象
    status: 0, //状态
  }

  let form = ref({ ...formDefault })

  const rules = {
    type: [{ required: true, message: '计费类型 必填' }],
    title: [{ required: true, message: '计费名称 必填' }],
    settleType: [{ required: true, message: '结算模式 必填' }],
    chargeType: [{ required: true, message: '计费模式 必填', trigger: 'change' }],
    stairType: [{ required: true, message: '阶梯类型 必填' }],
    chargeUserType: [{ required: true, message: '计费对象 必填' }],
    status: [{ required: true, message: '状态 必填' }],
  }

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields()
      save()
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!')
    }
  }
  const submitLoading = ref(false)
  // 新建、编辑API
  async function save() {
    submitLoading.value = true
    try {
      if (form.value.id) {
        await chargeUpdate(form.value)
        show(form.value.id)
      } else {
        await chargeInsert(form.value)
      }
      message.success('操作成功')
      onClose()
      emits('ok')
    } catch (err) {
      console.log(err)
      message.error('保存失败')
    } finally {
      submitLoading.value = false
    }
  }
  const onReset = () => {
    // 1.重置表单验证状态（不重置数据）
    formRef.value?.resetFields()
    form.value = cloneDeep(formDefault)
  }

  watch(
    [() => props.formId, () => props.open],
    (newVal) => {
      if ((props.formType == 'update' || props.formType == 'view') && props.open) {
        show(newVal[0])
        // console.log('data===>', data.value)
      }
    },
    { deep: true, immediate: true },
  )

  defineExpose({
    show,
  })
</script>

<style scoped>
  .section-title {
    font-size: 14px;
    font-weight: 500;
    margin: 24px 0 16px;
    color: #1f1f1f;
    position: relative;
    padding-left: 10px;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 4px;
      height: 16px;
      background-color: #1890ff;
    }
  }
  .note {
    color: red;
    font-size: 12px;
  }
</style>
